<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <title>聊天列表-在线聊天室</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/materialdesignicons.min.css"/>
    <style>
        /* 基础样式 */
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f5f5f5;
        }

        /* 聊天区域 */
        .chat-area {
            height: calc(100vh - 150px);
            overflow-y: auto;
            padding: 1rem;
            background-color: #fff;
            border-radius: 8px;
        }

        /* 消息输入区 */
        .chat-input {
            padding: 1rem;
            background-color: #fff;
            border-radius: 8px;
        }

        /* 消息通用样式 */
        .chat-message {
            margin-bottom: 1rem;
            display: flex;
        }

        .chat-message.left {
            justify-content: flex-start;
        }

        .chat-message.right {
            justify-content: flex-end;
            text-align: right;
        }

        /* 消息气泡 */
        .message-bubble {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            background-color: #e9ecef;
            display: inline-flex;
            align-items: flex-start;
            position: relative;
        }

        .chat-message.right .message-bubble {
            background-color: #94ea68;
        }

        /* 消息内容 */
        .message-content {
            margin-left: 10px;
            flex: 1;
        }

        /* 头像 */
        .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            object-fit: cover;
        }

        /* 文本消息 */
        .message-text {
            margin: 0;
            word-break: break-word;
            line-height: 1.4;
        }

        /* 图片消息 */
        .image-wrapper {
            max-width: 250px;
            border-radius: 8px;
            overflow: hidden;
            margin: 4px 0;
        }

        .chat-image {
            width: 100px;
            height: 100px;
        }

        /* 文件消息 */
        .file-message .message-bubble {
            background-color: #f8f9fa;
            padding: 8px;
        }

        .file-card {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .file-info {
            display: flex;
            align-items: center;
            flex: 1;
        }

        .file-icon {
            font-size: 24px;
            color: #4a6baf;
            margin-right: 10px;
        }

        .file-details {
            display: flex;
            flex-direction: column;
        }

        .file-name {
            font-weight: 500;
            color: #333;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 180px;
        }

        .file-meta {
            font-size: 12px;
            color: #6c757d;
        }

        .download-btn {
            color: #6c757d;
            font-size: 20px;
            margin-left: 10px;
            transition: all 0.2s;
        }

        .download-btn:hover {
            color: #007bff;
            transform: scale(1.1);
        }

        /* 时间戳 */
        .time-stamp {
            font-size: 11px;
            color: #6c757d;
            display: block;
            text-align: right;
            margin-top: 4px;
        }

        /* 欢迎消息 */
        .welcome-message {
            padding: 20px;
            margin-bottom: 20px;
            text-align: center;
        }

        .welcome-message h5 {
            margin-bottom: 5px;
            color: #007bff;
        }

        /* 工具栏 */
        .toolbar {
            padding: 10px;
            background-color: #fff;
            border-radius: 8px;
            margin-bottom: 10px;
        }

        /* 侧边栏 */
        .sidebar {
            background-color: #fff;
            height: calc(100vh - 20px);
            overflow-y: auto;
            border-right: 1px solid #eee;
        }

        .unread-badge {
            position: relative;
            display: inline-block;
        }

        .unread-count {
            position: absolute;
            top: 0;
            left: 50px;
            min-width: 16px;
            height: 16px;
            line-height: 16px;
            background-color: #ff4757;
            color: white;
            font-size: 10px;
            font-weight: bold;
            padding: 0 4px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
            animation: pulse 1.5s infinite;
            transform: translate(-50%, -50%);
        }

        @keyframes pulse {
            0% {
                transform: translate(-50%, -50%) scale(1);
            }
            50% {
                transform: translate(-50%, -50%) scale(1.1);
            }
            100% {
                transform: translate(-50%, -50%) scale(1);
            }
        }


        /* 隐藏元素 */
        .hide {
            display: none;
        }

        .list-group-item.active {
            background-color: #7ece56;
        }

        /* 消息发送者姓名 */
        .sender-name {
            display: block;
            color: #666;
            font-size: 12px;
            margin-bottom: 4px;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row pt-2">
        <!-- 侧边栏 -->
        <div class="col-md-3 bg-light p-3 sidebar">
            <div class="accordion" id="chatListsAccordion">
                <!-- 好友列表 -->
                <div class="card">
                    <div class="card-header p-0" id="friendsHeading">
                        <button class="btn btn-link btn-block text-left d-flex justify-content-between align-items-center"
                                type="button"
                                data-toggle="collapse"
                                data-target="#friendsCollapse"
                                aria-expanded="true"
                                aria-controls="friendsCollapse">
                            <span><i class="mdi mdi-account-multiple mr-2"></i>好友列表</span>
                            <span class="badge badge-primary badge-pill" th:text="${friends.size()}">0</span>
                        </button>
                    </div>
                    <div id="friendsCollapse" class="collapse show" aria-labelledby="friendsHeading"
                         data-parent="#chatListsAccordion">
                        <ul class="list-group list-group-flush friend-list">
                            <th:block th:each="friend : ${friends}">
                                <li class="list-group-item list-group-item-action d-flex align-items-center chat-item"
                                    th:attr="data-chatId=${'user-' +session.user.id+ '-'+ friend.id}">
                                    <img src="images/qq.png" th:src="${friend.avatar}" width="32" height="32"
                                         class="rounded-circle mr-2"/>
                                    <div class="chat-info">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span th:text="${friend.realName}" class="font-weight-bold"></span>
                                            <div class="unread-badge">
                                                <span class="unread-count"
                                                      th:class="${friend.unreadCount > 0 ? 'unread-count' : 'unread-count hide'}"
                                                      th:text="${friend.unreadCount}">
                                                    1
                                                </span>
                                            </div>
                                        </div>
                                        <div class="chat-status">
                                            <small class="text-muted" style="font-size: 11px;">[离线]</small>
                                        </div>
                                    </div>
                                </li>
                            </th:block>
                            <th:block th:if="${#lists.isEmpty(friends)}">
                                <li class="list-group-item text-muted">
                                    <i class="mdi mdi-emoticon-sad-outline mr-1"></i>暂无好友
                                </li>
                            </th:block>
                        </ul>
                    </div>
                </div>

                <!-- 群聊列表 -->
                <div class="card mt-2">
                    <div class="card-header p-0" id="groupsHeading">
                        <button class="btn btn-link btn-block text-left d-flex justify-content-between align-items-center"
                                type="button"
                                data-toggle="collapse"
                                data-target="#groupsCollapse"
                                aria-expanded="true"
                                aria-controls="groupsCollapse">
                            <span><i class="mdi mdi-account-group mr-2"></i>群聊列表</span>
                            <span class="badge badge-primary badge-pill" th:text="${groups.size()}">0</span>
                        </button>
                    </div>
                    <div id="groupsCollapse" class="collapse show" aria-labelledby="groupsHeading"
                         data-parent="#chatListsAccordion">
                        <ul class="list-group list-group-flush group-list">
                            <th:block th:each="group : ${groups}">
                                <li class="list-group-item list-group-item-action d-flex align-items-center chat-item"
                                    th:attr="data-chatId=${'group-' + group.id}">
                                    <img src="images/group.png" th:src="${group.avatar}" width="32" height="32"
                                         class="rounded-circle mr-2"/>
                                    <div class="chat-info">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span th:text="${group.name}" class="font-weight-bold"></span>
                                            <div class="unread-badge">
                                                <span class="unread-count"
                                                      th:class="${group.unreadCount > 0 ? 'unread-count' : 'unread-count hide'}"
                                                      th:text="${group.unreadCount}">
                                                    1
                                                </span>
                                            </div>
                                        </div>
                                        <div class="chat-status">
                                            <small class="text-muted" style="font-size: 11px;">
                                                <span id="online-total">1</span>
                                                人在线
                                            </small>
                                        </div>
                                    </div>
                                </li>
                            </th:block>
                            <th:block th:if="${#lists.isEmpty(groups)}">
                                <li class="list-group-item text-muted">
                                    <i class="mdi mdi-emoticon-sad-outline mr-1"></i>暂无群聊
                                </li>
                            </th:block>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <!-- 聊天窗口 -->
        <div class="col-md-9 main-content d-flex flex-column" style="height: calc(100vh - 20px);">
            <div class="chat-area flex-grow-1 mb-2" style="overflow-y: auto;">
                <!-- 欢迎消息 -->
                <div class="welcome-message text-center mb-4">
                    <h5 class="text-primary">欢迎使用在线聊天室！</h5>
                    <p class="text-muted">请选择一个聊天对象开始交流</p>
                </div>
            </div>

            <!-- 工具栏 -->
            <div class="d-flex align-items-center mb-2 toolbar">
                <button type="button" class="btn btn-sm btn-outline-secondary mr-2" id="emoji"
                        onclick="openEmoji()">
                    <i class="mdi mdi-emoticon-outline"></i> 表情
                </button>
                <button type="button" class="btn btn-sm btn-outline-secondary" id="upload" onclick="openUpload()">
                    <i class="mdi mdi-paperclip"></i> 文件
                </button>
                <input type="file" id="fileInput" style="display: none;">
            </div>

            <!-- 消息输入框 -->
            <div class="chat-input  flex-grow-0">
                <textarea class="form-control mb-1" id="message" rows="3" placeholder="输入消息..."
                          style="resize: none; border-radius: 15px;"></textarea>
                <small class="text-muted ml-2">按 Enter 发送，Shift+Enter 换行</small>
            </div>
        </div>
    </div>
</div>

<!-- 引入 JavaScript -->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/common.js"></script>

<!--在js脚本中获取作用域的值-->
<script th:inline="javascript">
    //获取session中的user
    var user = [[${session.user}]];
    //获取ws服务地址
    var ws = [[${ws}]]
</script>

<!-- 建立连接 -->
<script type="text/javascript">
    var websocket;
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        websocket = new WebSocket(ws + "?userId=" + user.id);
        websocket.onopen = function (event) {
            console.log("Netty-WebSocket服务器。。。。。。连接");
        };
        websocket.onmessage = function (event) {
            var json = JSON.parse(event.data);
            console.log('【接收消息】', json)
            chat.onmessage(json);
        };
        websocket.onclose = function (event) {
            console.log("Netty-WebSocket服务器。。。。。。关闭");
        };
    } else {
        alert("您的浏览器不支持WebSocket协议！");
    }
    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        if (websocket != null) {
            websocket.close();
        }
    };
</script>

<script>
    var chat = {
        // 发送消息给 websocket 对象
        sendMessage: function () {
            let message = $("#message").val().trim();
            // 判断消息是否为空
            if (message === "") {
                alert("不能发送空消息！")
                return
            }

            // 判断浏览器是否支持WebSocket
            if (!window.WebSocket) {
                return
            }

            // 获取聊天室id
            let chatId = formatChatId($(".list-group-item-action.active").attr("data-chatId"));

            if (!chatId) {
                alert('请选择聊天列表发送消息！')
                return
            }

            // 判断连接是否已经打开
            if (websocket.readyState === WebSocket.OPEN) {
                let data = {
                    chatId: chatId,
                    sendId: user.id,
                    content: message,
                    contentType: 'text',
                    isRead: false,
                    chatAvatar: user.avatar,
                    createTime: getNowTime(),
                    realName: user.realName,
                    fileType: '',
                    fileName: '',
                    fileSize: 0,
                }
                console.log('【发送消息】', data)
                websocket.send(JSON.stringify(data))

                // 添加消息
                $('.chat-area').append(buildMessage(data.chatId, data))
            } else {
                alert("和服务器连接异常！");
            }
        },

        // 接收消息
        onmessage: function (jsonData) {
            // 如果是初始化状态
            if (jsonData.chatType === "init_status") {
                jsonData.friends.forEach(friend => {
                    let chatId = "user-" + user.id + "-" + friend.userId
                    if (friend.status === 0) {
                        $(".list-group-item[data-chatId='" + chatId + "']").find('small').eq(0).html('<span style="color: green">[在线]</span>')
                    }
                })
                return
            }

            // 如果群聊在线人数消息
            if(jsonData.chatType === 'group_online'){
                $(".list-group-item[data-chatId='group-" + jsonData.groupId + "']").find('#online-total').text(jsonData.onlineCount)
                return
            }

            // 如果状态消息
            if (jsonData.chatType === 'status') {
                let chatId = "user-" + user.id + "-" + jsonData.userId
                if (jsonData.status === 0) {
                    $(".list-group-item[data-chatId='" + chatId + "']").find('small').eq(0).html('<span style="color: green">[在线]</span>')
                } else {
                    $(".list-group-item[data-chatId='" + chatId + "']").find('small').eq(0).html('[离线]')
                }

                return
            }

            // 如果是群聊并且是自己不添加消息
            if (jsonData.chatId.includes('group') && jsonData.sendId === user.id) {
                return
            }

            // 如果是当前聊天室才添加消息
            let chatId = $(".list-group-item.active").attr("data-chatId")
            if (jsonData.chatId == formatChatId(chatId)) {
                // 添加消息
                $('.chat-area').append(buildMessage(chatId, jsonData))
                $.post("/message/markAsRead/" + formatChatId(chatId), function (res) {
                })
            } else {
                let chatId = "user-" + user.id + "-" + jsonData.sendId
                if (jsonData.chatId.indexOf("user") === -1) {
                    chatId = jsonData.chatId;
                }
                let $unreadCount = $(".list-group-item[data-chatId='" + chatId + "']").find('.unread-count');
                $unreadCount.removeClass("hide");
                $unreadCount.text(eval($unreadCount.text()) + 1);
            }

            scrollToBottom();

        }
    }


    $(function () {
        // 监听消息输入框的按键事件
        $('#message').on('keydown', function (e) {
            // Enter 键的 keyCode 是 13
            if (e.keyCode === 13) {
                // 如果是 Shift+Enter (换行)
                if (e.shiftKey) {
                    // 允许默认行为（换行）
                    return true;
                }
                // 如果是普通 Enter (发送消息)
                else {
                    // 阻止默认行为（避免换行）
                    e.preventDefault();

                    // 发送消息
                    chat.sendMessage();

                    // 滚动到底部
                    scrollToBottom();

                    // 清空输入框
                    $(this).val('');
                }
            }
        });

        // 选择聊天对象
        $(".list-group-item-action").click(function () {
            $(".friend-list li, .group-list li").removeClass("active")
            $(this).addClass("active")

            let chatId = $(this).attr("data-chatId");
            // 初始化聊天记录
            initChatMessage(chatId);
        })
    })


    /**
     * 标记为已读
     * @param chatId 聊天ID
     */
    function markRead(chatId) {
        $.post("/message/markAsRead/" + formatChatId(chatId), function (res) {
            if (res.code === 200) {
                $(".list-group-item[data-chatId='" + chatId + "']").find('.unread-count').addClass("hide")
            }
        })
    }

    /**
     * 初始化聊天记录
     */
    function initChatMessage(chatId) {
        $.get("/message/" + formatChatId(chatId), function (res) {
            console.log("【聊天消息】", res.data)
            if (res.data.length === 0) {
                $('.chat-area').html("<p class='text-center text-muted empty-message'>暂时还没有消息！</p>")
            } else {
                let isRead = false;
                $('.chat-area').html("")
                res.data.forEach(item => {
                    if (item.isRead === 0) {
                        isRead = true;
                    }

                    $('.chat-area').append(buildMessage(chatId, item))
                })

                // 标记未读
                if (isRead) {
                    markRead(chatId)
                }

                // 滚动到底部
                scrollToBottom();
            }
        })
    }

    /**
     * 构建聊天记录
     * @param chatId 聊天ID
     * @param sendId 发送人
     * @param sender 方向
     * @param avatar 头像
     * @param time 时间
     * @param message 消息
     * @param type 消息类型
     * @returns {*|jQuery|HTMLElement}
     */
    function buildMessage(chatId, data) {
        $(".empty-message").removeClass("hide")
        $(".empty-message").addClass("hide")
        let $div = $(`<div class="chat-message ${user.id === data.sendId ? 'right' : 'left'}"></div>`);
        let $messageBubble = $("<div class='message-bubble'></div>");
        let $img = $(`<img class="avatar"  alt="头像"  src="${user.id === data.sendId ? user.avatar : data.chatAvatar}"/>`);
        $img.on('click', function () {
            if (user.id !== data.sendId) {
                if (chatId.indexOf('user') !== -1) {
                    window.location.href = `/detail/${chatId}`
                } else {
                    window.location.href = `/detail/${'user-' + user.id + "-" + data.sendId}`
                }
            } else {
                window.location.href = '/profile'
            }
        })
        let $messageContent;

        if (data.contentType === 'text') {
            $messageContent = $(`<div class="message-content">
                    ${appendName(chatId, data.sendId, data.realName)}
                    <p class="message-text">${data.content}</p>
                    <span class="time-stamp">${data.createTime}</span>
                </div>`)
        } else if (data.contentType === 'image') {
            $messageContent = $(` <div class="message-content">
                    ${appendName(chatId, data.sendId, data.realName)}
                    <div class="image-wrapper">
                        <img src="${data.content}" alt="图片消息"
                             class="chat-image"/>
                    </div>
                    <span class="time-stamp">${data.createTime}</span>
                </div>`)
        } else if (data.contentType === 'file') {
            $messageContent = $(`<div class="message-content">
                            ${appendName(chatId, data.sendId, data.realName)}
                            <div class="file-card">
                                <div class="file-info">
                                    <i class="${getFileIcon(data.fileType)} file-icon"></i>
                                    <div class="file-details">
                                        <span class="file-name">${data.fileName}</span>
                                        <span class="file-meta">${formatFileSize(data.fileSize)}</span>
                                    </div>
                                </div>
                                <a href="${data.content}" class="download-btn" title="下载文件">
                                    <i class="mdi mdi-download"></i>
                                </a>
                            </div>
                            <span class="time-stamp">${data.createTime}</span>
                        </div>`)
        }

        if (user.id !== data.sendId) {
            $messageBubble.append($img);
            $messageBubble.append($messageContent);
        } else {
            $messageBubble.append($messageContent);
            $messageBubble.append($img);
        }

        $div.append($messageBubble);

        return $div;
    }

    function appendName(chatId, sendId, realName) {
        if (chatId.indexOf('user') !== -1 || sendId === user.id) {
            return "";
        } else {
            return `<small class='sender-name'>${realName}</small>`;
        }
    }

    /**
     * 获取文件图标
     * @param fileType
     * @returns {*|string}
     */
    function getFileIcon(fileType) {
        const icons = {
            'text/plain': 'mdi mdi-file-document',
            'image/jpeg': 'mdi mdi-image',
            'video': 'mdi mdi-video',
            'audio': 'mdi mdi-music',
            'archive': 'mdi mdi-zip-box'
        };
        return icons[fileType] || 'mdi mdi-file';
    }

    /**
     * 格式化文件大小
     * @param bytes
     * @returns {string}
     */
    function formatFileSize(bytes) {
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
        return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
    }

    /**
     * 打开表情选择面板
     */
    function openEmoji() {
        // 显示表情选择面板
        let str = "😀 😃 😄 😁 😆 😅 🤣 😂 🙂 🙃 😉 😊 😇 🥰 😍 🤩 😘 😗 ☺ 😚 😙 🥲 😋 😛 😜 🤪 😝 🤑 🤗 🤭 🤫 🤔 🤐 🤨 😐 😑 😶 😏 😒 🙄 😬 🤥 😌 😔 😪 🤤 😴 😷 🤒 🤕 🤢 🤮 🤧 🥵 🥶 🥴 😵 🤯 🤠 🥳 🥸 😎 🤓 🧐 😕 😟 🙁 ☹ 😮 😯 😲 😳 🥺 😦 😧 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 🥱 😤 😡 😠 🤬 😈 👿 💀 ☠ * 🤡 👹 👺 👻 👽 👾 🤖 😺 😸 😹 😻 😼 😽 🙀 😿 😾 🙈 🙉 🙊 💋 💌 💘 💝 💖 💗 💓 💞 💕 💟 ❣ 💔 ❤ 🧡 💛 💚 💙 💜 🤎 🖤 🤍 💯 💢 💥 💫 💦 💨 🕳 💣 💬 👁‍🗨 🗨 🗯 💭 💤";
        var emojis = str.split(" ");

        // 获取表情按钮的位置
        var emojiButton = document.getElementById('emoji');
        var buttonRect = emojiButton.getBoundingClientRect();

        // 创建表情面板
        var emojiList = document.createElement('div');
        emojiList.id = 'emojiList';
        emojiList.className = 'card';
        emojiList.style.position = 'fixed';
        emojiList.style.left = buttonRect.left + 'px';
        emojiList.style.bottom = (window.innerHeight - buttonRect.top + 10) + 'px';
        emojiList.style.width = '300px';
        emojiList.style.maxHeight = '200px';
        emojiList.style.backgroundColor = '#f5f5f5';
        emojiList.style.padding = '10px';
        emojiList.style.borderRadius = '5px';
        emojiList.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.1)';
        emojiList.style.zIndex = '1000';
        emojiList.style.overflowY = 'auto';

        var emojiContainer = document.createElement('div');
        emojiContainer.style.display = 'flex';
        emojiContainer.style.flexWrap = 'wrap';
        emojiContainer.style.gap = '5px';

        emojis.forEach(function (emoji) {
            var span = document.createElement('span');
            span.textContent = emoji;
            span.style.cursor = 'pointer';
            span.style.fontSize = '20px';
            span.addEventListener('click', function () {
                document.getElementById('message').value += emoji;
            });
            emojiContainer.appendChild(span);
        });

        emojiList.appendChild(emojiContainer);

        document.body.appendChild(emojiList);

        // 点击其他地方隐藏表情面板
        document.addEventListener('click', function (event) {
            if (!event.target.closest('#emoji') && !event.target.closest('#emojiList')) {
                emojiList.remove();
            }
        });
    }


    /**
     * 格式化聊天ID
     * @param chatId
     * @returns {*|string}
     */
    function formatChatId(chatId) {
        if (chatId != null && chatId.indexOf("user") !== -1) {
            const arr = chatId.split("-").slice(1)
            const sender = arr[0]
            const receiver = arr[1]

            if (sender < receiver) {
                return `user-${sender}-${receiver}`;
            } else {
                return `user-${receiver}-${sender}`;
            }
        } else {
            return chatId;
        }
    }


    /**
     * 滚动到底部
     */
    function scrollToBottom() {
        let chatArea = $('.chat-area');
        chatArea.scrollTop(chatArea[0].scrollHeight);
    }

</script>

<script type="text/javascript">
    $(document).ready(function () {
        // 文件选择事件
        $("#fileInput").change(function () {
            // 获取聊天室id
            let chatId = formatChatId($(".list-group-item-action.active").attr("data-chatId"));

            let file = $("#fileInput")[0].files[0];
            if (file == null) {
                return;
            }

            const fileName = file.name;
            const ext = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
            const fileType = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext) ? 'image' : 'file';

            let formData = new FormData();
            formData.append("file", file);
            $.ajax({
                url: "/file/upload",
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                success: function (res) {
                    let result = res.data;
                    if (websocket.readyState === WebSocket.OPEN) {
                        let data = {
                            chatId: chatId,
                            sendId: user.id,
                            content: result.filePath,
                            contentType: fileType,
                            fileId: result.id,
                            chatAvatar: user.avatar,
                            createTime: getNowTime(),
                            realName: user.realName,
                            fileName: result.originalName,
                            fileSize: result.fileSize,
                            fileType: result.fileType
                        }
                        console.log('send message', data)
                        websocket.send(JSON.stringify(data))

                        // 添加消息
                        $(".chat-area").append(buildMessage(data.chatId, data));
                        scrollToBottom();
                    } else {
                        alert("和服务器连接异常！");
                    }
                },
                error: function () {
                    alert("上传失败");
                }
            })
        });
    });

    // 打开文件上传
    function openUpload() {
        // 获取聊天室id
        let chatId = formatChatId($(".list-group-item-action.active").attr("data-chatId"));

        if (!chatId) {
            alert('请先选择聊天列表对象！')
            return
        }

        $("#fileInput").click();
    }


    // 获取url参数
    window.onload = function () {
        const urlParams = new URLSearchParams(window.location.search);
        let chatId = urlParams.get('chatId');

        if (chatId != null && chatId.indexOf("user") !== -1) {
            let arr = chatId.split("-");
            chatId = `${arr[0]}-${user.id}-${arr[1]}`
        }

        $(`[data-chatId='${chatId}']`).click();
    }


</script>
</body>
</html>